package com.shanzmoo.base.bean;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.annotation.JsonIgnore;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import springfox.documentation.annotations.ApiIgnore;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.io.Serializable;

import static cn.hutool.core.util.StrUtil.COMMA;
import static cn.hutool.core.util.StrUtil.toUnderlineCase;

/**
 * @Description  分页请求基础类
 * @Author       guizhao
 * @Date         2020/4/9 15:08
 */
@Data
public class PageReqBase implements Serializable {

    @NotNull
    @Min(1)
    @Max(100000)
    @ApiModelProperty(name = "pageNum", value = "当前页", example = "1", required = true)
    private Long pageNum = 1L;

    @NotNull
    @Min(1)
    @Max(500)
    @ApiModelProperty(name = "pageSize", value = "每页数量", example = "10", required = true)
    private Long pageSize = 10L;

    @ApiModelProperty(value = "排序字段")
    protected String sortField;

    @ApiModelProperty(value = "排序方向[asc,desc]", example = "asc")
    protected String sortOrder;

    @ApiModelProperty(value = "是否导出excel")
    protected Boolean exportExcel = false;

    @JsonIgnore
    @ApiModelProperty(value = "导出最大查询的数据", hidden = true)
    protected Long exportMaxLimit = -1L;

    /**
     * 获取page对象，默认开启排序
     *
     * @return page对象
     */
    @JsonIgnore
    @ApiIgnore
    public Page page() {
        return page(true);
    }

    /**
     * 获取page对象
     *
     * @param sort false表示不添加排序
     * @return page对象
     */
    @JsonIgnore
    @ApiIgnore
    public Page page(boolean sort) {
        Page page = new Page(getPageNum(), getExportExcel() ? getExportMaxLimit() : getPageSize());
        page.setSearchCount(!getExportExcel());
        // 不为空时添加排序字段
        if (sort && StrUtil.isNotBlank(getSortField())) {
            // 如果是多个按,分割
            String[] fields = StrUtil.split(getSortField(), COMMA);
            for (String field : fields) {
                OrderItem orderItem = new OrderItem();
                orderItem.setColumn(toUnderlineCase(field));
                // 为空设置为升序
                orderItem.setAsc(StrUtil.isBlank(getSortOrder()) || StrUtil.equalsIgnoreCase(getSortOrder(), "asc"));
                page.addOrder(orderItem);
            }
        }
        return page;
    }
}
